<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Socket.IO Chat</title>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      let socket;
      let token = "";
      let user = "";
      // 页面加载时检查 localStorage 中是否有 token
      window.onload = function () {
        token = localStorage.getItem("token");
        if (token) {
          user = localStorage.getItem("user");
          // 如果有 token，则创建 Socket 连接并获取历史消息
          createSocketConnection(token); // 如果有 token，则建立 Socket 连接
          domclear();
          fetchMessages(); // 获取历史消息
          setlogin(user);
          fetchFriends();
        }
      };

      function register() {
        const username = document.getElementById("register-username").value;
        const password = document.getElementById("register-password").value;

        fetch("/register", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ username, password }),
        })
          .then((response) => response.json())
          .then((data) => alert(data.message || data.error));
      }

      function login() {
        const username = document.getElementById("login-username").value;
        const password = document.getElementById("login-password").value;

        fetch("/login", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ username, password }),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.token) {
              token = data.token;
              localStorage.setItem("user", username);
              localStorage.setItem("token", token);
              user = username;
              setlogin(username);

              createSocketConnection(token); // 登录成功后创建 Socket 连接
              domclear(); // ��空消息列表
              fetchMessages(); // 登录后获取历史消息
              fetchFriends(); // 获取好友列表
            } else {
              alert(data.error);
            }
          });
      }
      function setlogin(data) {
        document.getElementById("loginname").innerHTML = data;
      }

      function createSocketConnection(token) {
        // 创建 Socket.IO 连接，并将 token 作为查询参数传递
        socket = io({ query: { token } });

        socket.on("connect", () => {
          console.log("Socket connected");
        });

        socket.on("chat message", (msg) => {
          appendMessage(msg);
        });
        // 处理清空消息
        socket.on("clear messages", () => {
          document.getElementById("messages").innerHTML = ""; // 清空消息列表
        });

        socket.on("private message", ({ sender, message }) => {
          const item = document.createElement("li");
          item.textContent = `来自 ${sender} 的私信: ${message}`;
          item.style.fontStyle = "italic"; // 用不同的样式显示私聊消息
          document.getElementById("messages").appendChild(item);
        });

        socket.on("update user list", (users) => {
          const userList = document.getElementById("user-list");
          userList.innerHTML = ""; // 清空现有列表
          users.forEach((username) => {
            const userItem = document.createElement("li");
            userItem.textContent = username;

            // 如果用户名不是当前用户自己，则添加点击事件
            if (username !== user) {
              userItem.style.cursor = "pointer"; // 表示可以点击
              userItem.onclick = () => startPrivateChat(username);

              // 添加 "加好友" 按钮
              const addFriendButton = document.createElement("button");
              addFriendButton.textContent = "加好友";

              addFriendButton.onclick = (event) => {
                event.stopPropagation(); // 阻止事件冒泡
                addFriend(username); // 调用添加好友的函数
              };
              userItem.appendChild(addFriendButton);
            }
            userList.appendChild(userItem);
          });
        });

        socket.on("revoke message", (messageId) => {
          const item = document.querySelector(`li[data-id="${messageId}"]`);
          if (item) {
            item.remove();
          }
        });
      }

      function clearMessages() {
        fetch("/messages", {
          method: "DELETE",
        }).then((response) => {
          if (response.ok) {
            console.log("Chat history cleared");
          } else {
            console.error("Failed to clear chat history");
          }
        });
      }

      function fetchFriends() {
        fetch("/get-friends", {
          method: "GET",
          headers: {
            Authorization: `Bearer ${token}`, // 发送用户的 token 进行身份验证
          },
        })
          .then((response) => response.json())
          .then((friends) => {
            const friendList = document.getElementById("friend-list");
            friendList.innerHTML = ""; // 清空现有列表
            friends.forEach((friend) => {
              const friendItem = document.createElement("li");
              friendItem.textContent = friend.username;
              friendItem.onclick=() => openChatWithFriend(friend.username);
              friendList.appendChild(friendItem);
            });
          })
          .catch((err) => console.error("Error fetching friends:", err));
      }

      function domclear() {
        const messages = document.getElementById("messages");
        messages.innerHTML = "";
      }

      function openChatWithFriend(friendUsername) {
    const url = `chat.html?friend=${friendUsername}`;
    window.open(url, '_blank'); // 打开一个新的标签页
}

      function sendMessage() {
        if (localStorage.getItem("user") == null) {
          alert("You need to login first");
          return; // 若未登录，则返回并不执行后面的代码
        }
        const messageInput = document.getElementById("message");
        const message = messageInput.value;
        socket.emit("chat message", message);
        messageInput.value = "";
        return false; // 防止表单提交
      }

      // 获取历史消息
      async function fetchMessages() {
        const response = await fetch("/messages");
        const messages = await response.json();
        messages.forEach((msg) => {
          appendMessage(msg);
        });
      }

      function appendMessage(msg) {
        const item = document.createElement("li");
        item.textContent = msg.content;
        item.setAttribute("data-id", msg._id);
        item.setAttribute("data-sender", msg.sender);

        if (msg.sender === user) {
          const revokeButton = document.createElement("button");
          revokeButton.textContent = "撤回";
          revokeButton.onclick = () => revokeMessage(msg._id);
          item.appendChild(revokeButton);
        } else {
          item.style.cursor = "pointer"; // 表明该消息是可点击的
          item.onclick = () => startPrivateChat(msg.sender);
        }

        document.getElementById("messages").appendChild(item);
      }

      function addFriend(friendUsername) {
        event.preventDefault();
        fetch("/add-friend", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${localStorage.getItem("token")}`, // 发送用户的 token 进行身份验证
          },
          body: JSON.stringify({ friendUsername }),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data.message) {
              //   alert("好友添加成功");
              console.log("好友添加成功");
            } else {
              //   alert(data.error || "添加好友失败");
              console.log("好友添加失败");
            }
          })
          .catch((err) => console.error("Error adding friend:", err));
      }

      function logout() {
        localStorage.removeItem("token");
        localStorage.removeItem("user");
        if (socket) socket.disconnect();
        window.location.reload(); // Reload the page to reset the state
      }
      function revokeMessage(messageId) {
        socket.emit("revoke message", messageId);
      }

      function startPrivateChat(recipient) {
        const privateMessage = prompt(`发送私信给 ${recipient}:`);
        if (privateMessage) {
          socket.emit("private message", {
            recipient,
            message: privateMessage,
          });
        }
      }
    </script>
  </head>
  <body>
    <h1>Chat Application</h1>
    <h2>Register</h2>
    <input id="register-username" placeholder="Username" required />
    <input
      id="register-password"
      placeholder="Password"
      type="password"
      required
    />
    <button onclick="register()">Register</button>

    <h2>Login</h2>
    <input id="login-username" placeholder="Username" required />
    <input
      id="login-password"
      placeholder="Password"
      type="password"
      required
    />
    <button onclick="login()">Login</button>

    <h2 id="loginname"></h2>
    <h2>在线用户</h2>
    <ul id="user-list"></ul>
    <h2>好友列表</h2>
    <ul id="friend-list"></ul>
    <h2>聊天内容</h2>
    <ul id="messages"></ul>
    <form onsubmit="return sendMessage();">
      <input id="message" autocomplete="off" placeholder="Type a message..." />
      <button>Send</button>
    </form>
    <button onclick="clearMessages()">Clear Chat History</button>
    <button onclick="logout()">Logout</button>
  </body>
</html>
